package com.shxc.smarttrade.old.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.adapter.FollowOrderDetailAdapter;
import com.shxc.smarttrade.MyApplication;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.FollowMasterDetail;
import com.shxc.smarttrade.old.bean.MasterCopyInfo;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.iview.SupermandetailIView;
import com.shxc.smarttrade.old.myview.CustomDialog;
import com.shxc.smarttrade.old.myview.MyFootView;
import com.shxc.smarttrade.old.myview.MyRefreshHeadView;
import com.shxc.smarttrade.old.myview.RecycleViewDivider;
import com.shxc.smarttrade.old.presenter.MasterDetailPresenter;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.BaseView;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.zhy.autolayout.AutoLinearLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/9/27.
 */

public class FollowOrderDetailActivity extends BaseActivity implements SupermandetailIView {
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.ll_title_all)
    AutoLinearLayout llTitleAll;
    @BindView(R.id.tv_follow_name)
    TextView tvFollowName;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.tv_now_profits)
    TextView tvNowProfits;
    @BindView(R.id.tv_position_profit)
    TextView tvPositionProfit;
    @BindView(R.id.tv_follow_money)
    TextView tvFollowMoney;
    @BindView(R.id.x_recycler_view)
    XRecyclerView xRecyclerView;
    @BindView(R.id.ll_followed)
    AutoLinearLayout llFollowed;
    @BindView(R.id.ll_nodata_bg)
    LinearLayout llNodataBg;
    private LinearLayoutManager manager;
    private PopupWindow popupWindow = null;
    private MasterDetailPresenter masterDetailPresenter = new MasterDetailPresenter(this);
    private String accessToken = "";
    private int userId = -1;
    private String userCode = "";
    private MasterCopyInfo.DataBean.CopyInfoBean masterCopyInfo = null;
    private View view = null;
    private FollowOrderDetailAdapter adapter;
    private String userName = "";
    private String headUrl = "";
    private int id = -1;


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    FollowMasterDetail fmd = (FollowMasterDetail) msg.obj;
                    FollowMasterDetail.DataBean.MasterDetailBean md = fmd.getData().getMasterDetail();
                    List<FollowMasterDetail.DataBean.HisCopyListBean> hisCopyList = fmd.getData().getHisCopyList();
                    tvStartTime.setText(BaseUtils.getDateFromMillionSeconds(md.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
                    if (md.getCurrentCopyProfit() < 0) {
                        tvNowProfits.setTextColor(getResources().getColor(R.color.stock_fell_color));
                        tvNowProfits.setText("-$" + BaseUtils.getDigitsData(Math.abs(md.getCurrentCopyProfit()), 2));
                    } else {
                        tvNowProfits.setTextColor(getResources().getColor(R.color.stock_rise_color));
                        tvNowProfits.setText("$" + BaseUtils.getDigitsData(Math.abs(md.getCurrentCopyProfit()), 2));
                    }

                    if (md.getCloseCopyProfit() < 0) {
                        tvPositionProfit.setTextColor(getResources().getColor(R.color.stock_fell_color));
                        tvPositionProfit.setText("-$" + BaseUtils.getDigitsData(Math.abs(md.getCloseCopyProfit()), 2));
                    } else {
                        tvPositionProfit.setTextColor(getResources().getColor(R.color.stock_rise_color));
                        tvPositionProfit.setText("$" + BaseUtils.getDigitsData(Math.abs(md.getCloseCopyProfit()), 2));
                    }
                    tvFollowMoney.setText("$" + BaseUtils.getDigitsData(md.getAmt(), 2));
                    if (hisCopyList == null || hisCopyList.size() == 0)
                        llNodataBg.setVisibility(View.VISIBLE);
                    else {
                        llNodataBg.setVisibility(View.GONE);
                        adapter.setDatas(hisCopyList);
                    }

                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_follow_order_detail);
        initView();
        initData();
    }


    private void initView() {
        tvCenter.setText("跟单详情");
        manager = new LinearLayoutManager(this);
        xRecyclerView.setLayoutManager(manager);
        xRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayout.VERTICAL, 2, getResources().getColor(R.color.all_background)));
        xRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
        MyRefreshHeadView myRefreshHeadView = new MyRefreshHeadView(this);
        myRefreshHeadView.setArrowImageView(R.mipmap.indicator_arrow);
        xRecyclerView.setRefreshHeader(myRefreshHeadView);
        xRecyclerView.setFootView(new MyFootView(this));
        xRecyclerView.setLoadingMoreEnabled(false);
        xRecyclerView.setPullRefreshEnabled(false);
        xRecyclerView.setAdapter(adapter = new FollowOrderDetailAdapter(this));

    }

    private void initData() {
        userCode = getIntent().getStringExtra("userCode");
        userName = getIntent().getStringExtra("userName");
        headUrl = getIntent().getStringExtra("headUrl");
        id = getIntent().getIntExtra("id", -1);
        tvFollowName.setText("跟单 " + userName + " 详情");
        accessToken = SpUtils.getString(this, "accessToken", "");
        userId = SpUtils.getInt(this, "userId", -1);
        getMasterDetails();
    }

    @OnClick({R.id.btn_go_master, R.id.btn_change_money, R.id.btn_remove, R.id.rl_left})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_go_master:
                //进入高手主页
                Intent intent = new Intent(this, SupermanDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("userCode", userCode);
                bundle.putString("userName", userName);
                bundle.putString("headUrl", headUrl);
                bundle.putInt("where", 3);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.btn_change_money:
                showShortDialog();
                masterDetailPresenter.getMasterCopyInfo(accessToken, userId, userCode);
                break;
            case R.id.btn_remove:
                showRemoveFollowDialog();
                break;
            case R.id.rl_left:
                finish();
                break;
        }
    }


    /**
     * 修改／跟随高手
     *
     * @param etMoney
     * @param btnSure
     */
    private void showFollowMasterPopupWindow(final EditText etMoney, Button btnSure) {
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String money = etMoney.getText().toString().trim();
                try {
                    double moneyD = Double.valueOf(money);
                    if (moneyD < masterCopyInfo.getMinAmt()) {
                        showMyToast("不能小于最低跟单金额");
                        return;

                    } else if (moneyD > masterCopyInfo.getAvailableAmt()) {
                        showMyToast("不能超出账户可用余额");
                        return;
                    }
                } catch (Exception e) {
                    showMyToast("请输入有效金额");
                    return;
                }
                if (!TextUtils.isEmpty(money)) {
                    masterDetailPresenter.copyMaster(accessToken, userId, userCode, money, 1);
                    if (popupWindow != null)
                        popupWindow.dismiss();

                } else {
                    MyApplication.showToast(getApplicationContext(), "复制金额不能为空");
                }

            }
        });
    }


    /**
     * 解除跟随关系对话框
     */
    private void showRemoveFollowDialog() {
        CustomDialog menuDialog = new CustomDialog(this, R.style.customDialogStyle);
        menuDialog.setCancelable(true);
        //取消复制并跟随高手平仓
        menuDialog.setTakePhotoRunnable(new Runnable() {
            @Override
            public void run() {
                masterDetailPresenter.cancelMasterCopy(accessToken, userId, userCode, 0);
            }
        });
        //取消复制并强制平仓
        menuDialog.setTakePictureRunnable(new Runnable() {
            @Override
            public void run() {
                masterDetailPresenter.cancelMasterCopy(accessToken, userId, userCode, 1);
            }
        });
        menuDialog.show();
    }

    private void getMasterDetails() {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", accessToken);
        map.put("userId", String.valueOf(userId));
        map.put("userCode", userCode);
        map.put("id", String.valueOf(id));
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.FOLLOW_MASTER_DETAIL, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showMyToast("网络异常");
            }

            @Override
            public void success(String response, int id) {
                if (response == null || new JsonParser().parse(response).isJsonNull()) {
                    return;
                }
                Gson gson = new Gson();
                FollowMasterDetail fd = gson.fromJson(response, FollowMasterDetail.class);
                if (fd.getErr_code().equals("0")) {
                    Message msg = Message.obtain();
                    msg.what = 0;
                    msg.obj = fd;
                    handler.sendMessage(msg);
                } else {
                    showMyToast(fd.getErr_msg());
                }

            }
        });
    }


    @Override
    public void showDialog() {
        showShortDialog();
    }

    @Override
    public void dismissDialog() {
        dismissShortDialog();
    }

    @Override
    public void showMyToast(String str) {
        dismissShortDialog();
        showToast(str);
    }

    @Override
    public void showMasterCopyInfo(MasterCopyInfo.DataBean.CopyInfoBean masterCopyInfo) {
        dismissShortDialog();
        if (llFollowed == null) return;
        this.masterCopyInfo = null;
        this.masterCopyInfo = masterCopyInfo;
        if (view == null)
            view = View.inflate(this, R.layout.pop_style_follow_order, null);
        TextView tvPopName = (TextView) view.findViewById(R.id.tv_pop_name);
        ImageView ivDiss = (ImageView) view.findViewById(R.id.iv_diss);
        final EditText etMoney = (EditText) view.findViewById(R.id.et_money);
        LinearLayout llOne = (LinearLayout) view.findViewById(R.id.ll_one);
        TextView tvOne = (TextView) view.findViewById(R.id.tv_one);
        TextView tvTwo = (TextView) view.findViewById(R.id.tv_two);
        TextView tvThree = (TextView) view.findViewById(R.id.tv_three);
        TextView tvFour = (TextView) view.findViewById(R.id.tv_four);
        TextView tvFourLeft = (TextView) view.findViewById(R.id.tv_four_left);
        Button btnSure = (Button) view.findViewById(R.id.btn_sure);
        if (masterCopyInfo == null) {
            showMyToast("暂无法修改 请稍后重试");
            return;
        }
        btnSure.setText("确认修改");
        tvPopName.setText("修改跟单金额");
        llOne.setVisibility(View.VISIBLE);
        tvOne.setText("$" + BaseUtils.getDigitsData(masterCopyInfo.getUsedAmt(), 2));
        tvTwo.setText("$" + BaseUtils.getDigitsData(masterCopyInfo.getAvailableAmt(), 2));
        tvThree.setText("$" + BaseUtils.getDigitsData(masterCopyInfo.getAdviceAmt(), 2));
        tvFour.setText("$" + BaseUtils.getDigitsData(masterCopyInfo.getMinAmt(), 2));
        popupWindow = BaseView.showPopupWindow(view, this, R.layout.activity_superman_detail, Gravity.CENTER);
        ivDiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow != null)
                    popupWindow.dismiss();
            }
        });
        showFollowMasterPopupWindow(etMoney, btnSure);
    }

    @Override
    public void showMasterCopyMasterResult(String result) {
        showMyToast(result);
        getMasterDetails();
        EventBus.getDefault().post(new EventDatas(EventContents.FOLLOW_ORDER_DETAIL_ACTIVITY, ""));
    }

    @Override
    public void showMasterCancleCopyResult(String result) {
        showMyToast(result);
        EventBus.getDefault().post(new EventDatas(EventContents.FOLLOW_ORDER_DETAIL_ACTIVITY, ""));
        EventBus.getDefault().post(new EventDatas(EventContents.STOP_LOSS_OR_PROFIT_FINISH_TRADE, null));
        finish();
    }
}
